// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { NumberDivide, FormatnumberZero, Mover } from '@/function.js';

// 视图插件
import {
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

// css OR less预编译器
import styles from './RiskControl.less';
import RiskDetail from './RiskDetail.js';
import { getShareOptionRiskData } from '../../../services/riskcontrol_service';

// 图片

// 算式

/* 补零 */

/* 切割日期 */
function StringSplit(date) {
  // 日期
  if (typeof date === 'string') {
    return date.split(' ')[0];
  }
  return null;
}
function TimeContact() {
  // 当前日期
  let timeform;
  const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  timeform = `${year}/${month}/${day}`;
  return timeform;
}
function DateDiffToo(sDate1, sDate2) {
  // sDate1和sDate2是yyyy-MM-dd格式
  let aDate;
  let oDate1;
  let oDate2;
  let iDays;
  aDate = sDate1.split('-');
  oDate1 = new Date(`${aDate[1]}-${aDate[2]}-${aDate[0]}`); // 转换为yyyy-MM-dd格式
  aDate = sDate2.split('-');
  oDate2 = new Date(`${aDate[1]}-${aDate[2]}-${aDate[0]}`);
  iDays = parseInt(Math.abs(oDate1 - oDate2) / 950 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
  return iDays; // 返回相差天数
}
function DateDiffTooResults(sDate2) {
  // sDate1和sDate2是yyyy-MM-dd格式
  if (typeof sDate2 === 'string') {
    let aDate;
    let oDate1;
    let oDate2;
    let iDays;
    oDate1 = new Date(); // 转换为yyyy-MM-dd格式
    aDate = sDate2.split('/');
    oDate2 = new Date(`${aDate[1]}-${aDate[2]}-${aDate[0]}`);
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 950 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
    return iDays; // 返回相差天数
  }
  return '暂无数据';
}
function DateStamp(param) {
  // sDate1和sDate2是yyyy-MM-dd格式
  const str = param.replace(/-/g, '/');
  const date = new Date(str);
  date.setDate(date.getDate() + 1);
  return date; // 返回相差天数
}

/**
 *  Created by xjc on 2019/5/15
 *  Describe:数据连接
 */

@connect(({ riskstock, loading }) => ({
  riskstock,
  loading: loading.models.riskControlRule,
}))
@Form.create()
class RiskControlTwo extends PureComponent {
  componentWillMount() {}

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    RiskDetailVisible: false, // modal开关
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
  };

  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 90, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 90 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1890ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes(value.toLowerCase()),
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:表头
   */
  columns = [
    {
      title: 'ID',
      /* colSpan:0, */
      dataIndex: 'id',
      /* render: (value, row, index) => {
         const obj = {
           children: value,
           props: {},
         };
         obj.props.rowSpan = 0;
         return obj;
       } */
    },
    {
      title: '股票代码',

      width: 95,
      dataIndex: 'stock',
      ...this.getColumnSearchProps('stock'),
    },
    {
      title: '风险等级标记',
      align: 'center',

      width: 95,
      dataIndex: 'risklevel',
      render: (value, row, index) => {
        let color = '';
        let name = '';
        switch (value) {
          case 1:
            name = '低级';
            color = '#262626';
            break;
          case 2:
            name = '中级';
            color = '#262626';
            break;
          case 3:
            name = '高级';
            color = '#ff4d4f';
            break;
        }
        return <span style={{ color }}>{name}</span>;
      },
    },
    {
      title: '成本价',
      width: 95,
      dataIndex: 'costprice',
    },
    {
      title: '最新价',
      width: 95,
      dataIndex: 'nowprice',
    },
    {
      title: '数量（股）',
      width: 95,
      sorter: (a, b) => a.stocknumber - b.stocknumber,
      dataIndex: 'stocknumber',
      render: (value, row, index) => {
        return <span>{NumberDivide(value.toString())}</span>;
      },
    },
    {
      title: '市值',
      width: 95,
      sorter: (a, b) => a.marketvalue - b.marketvalue,
      dataIndex: 'marketvalue',
      render: (value, row, index) => {
        return <span>{NumberDivide(value.toString())}</span>;
      },
    },
    {
      title: '持仓比例',
      width: 95,
      sorter: (a, b) => a.positionpercent - b.positionpercent,
      dataIndex: 'positionpercent',
      render: (value, row, index) => {
        let color = '';
        if (value > 0.25) {
          color = '#ff4d4f';
        } else {
          color = '#262626';
        }
        return <span style={{ color }}>{`${FormatnumberZero(value * 100, 2)}%`}</span>;
      },
    },
    {
      title: '当日盈亏',
      width: 95,
      sorter: (a, b) => a.todayprofit - b.todayprofit,
      dataIndex: 'todayprofit',
      render: (value, row, index) => {
        return <span>{NumberDivide(value.toString())}</span>;
      },
    },
    {
      title: '盈亏',
      width: 105,
      sorter: (a, b) => a.profit - b.profit,
      dataIndex: 'profit',
      render: (value, row, index) => {
        return <span>{NumberDivide(value.toString())}</span>;
      },
    },
    {
      title: '盈亏百分比',
      width: 95,
      sorter: (a, b) => a.profitpercent - b.profitpercent,
      dataIndex: 'profitpercent',
    },
    {
      title: '财报日期',
      width: 120,
      sorter: (a, b) => DateStamp(a.reportdate) - DateStamp(b.reportdate),
      dataIndex: 'reportdate',
      render: (value, row, index) => {
        let color = '#262626';
        if (row.colorresultsflag) {
          color = '#ff4d4f';
        } else {
          color = '#262626';
        }
        return <div style={{ color }}>{StringSplit(value)}</div>;
      },
    },
    {
      title: '报警百分比',
      width: 95,
      sorter: (a, b) => a.alertpercent - b.alertpercent,
      dataIndex: 'alertpercent',
      render: (value, row, index) => {
        let color = '';
        if (value > 0.1) {
          color = '#ff4d4f';
        } else {
          color = '#262626';
        }
        return <span style={{ color }}>{`${FormatnumberZero(value * 100, 2)}%`}</span>;
      },
    },
    {
      title: '所属行业',
      width: 95,
      dataIndex: 'trade',
    },
    {
      title: '行业集中度仓位比',
      width: 95,
      sorter: (a, b) => a.tradepercent - b.tradepercent,
      dataIndex: 'tradepercent',
      render: (value, row, index) => {
        let color = '';
        if (value > 0.35) {
          color = '#ff4d4f';
        } else {
          color = '#262626';
        }
        return <span style={{ color }}>{`${FormatnumberZero(value * 100, 2)}%`}</span>;
      },
    },
    {
      title: '剩余sellcall',
      width: 95,
      /*  render: (value, row, index) => {

          return <span style={{color: '#262626'}}>暂无</span>
        } */
    },
    {
      title: '剩余sellput',
      width: 95,
      /* render: (value, row, index) => {

         return <span style={{color: '#262626'}}>暂无</span>
       } */
    },
    {
      title: '操作时间',
      width: 110,
      sorter: (a, b) => DateStamp(a.addtime) - DateStamp(b.addtime),
      dataIndex: 'addtime',
      render: (value, row, index) => {
        return <div style={{}}>{value}</div>;
      },
    },
    {
      title: '操作',
      align: 'right',
      width: 95,
      key: 'operation',
      render: (value, row, index) => <a onClick={this.changeRecord.bind(this, value)}>编辑</a>,
    },
  ];

  changeRecord(record) {
    this.setState({
      record,
      RiskDetailVisible: true,
    });
  }

  closeRecord() {
    const { dispatch } = this.props;
    this.setState(
      {
        RiskDetailVisible: false,
      },
      () => {
        /* 导入列表数据 */
        dispatch({
          type: 'riskstock/GetRiskDataTwo',
          payload: {},
          callback: res => {},
        });
      }
    );
  }

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:视图
   */

  render() {
    const {
      loading,
      riskstock: { riskDataTwo },
    } = this.props;
    const { listLoading, selectedRows, record, RiskDetailVisible } = this.state;
    const listData = {
      list: [],
    };
    const expandedRowKeys = [];
    if (riskDataTwo.code === 1) {
      listData.list = riskDataTwo.data;
      for (let i = 0; i < listData.list.length; i++) {
        const item = listData.list[i];
        // 剩余日子
        const sDate1 = TimeContact(item.expiry);
        const sDate2 = TimeContact(new Date());
        const sDate = DateDiffToo(sDate1, sDate2);
        item.remaindays = sDate;
        // 自动展开
        const markType = typeof item.mark;
        if (item.mark !== '' && item.mark !== null && markType !== 'undefined') {
          expandedRowKeys.push(item.id);
        }
        // 财报日标志
        const DateDiffResults = DateDiffTooResults(item.reportdate);
        if (DateDiffResults !== '暂无数据') {
          if (DateDiffResults < 4) {
            item.colorresultsflag = true;
          }
        } else {
          item.colorresultsflag = false;
        }
        // 报警标志
        if (
          item.positionpercent > 0.25 ||
          item.tradepercent > 0.35 ||
          item.alertpercent > 0.1 ||
          item.colorresultsflag ||
          item.risklevel === 3
        ) {
          item.colorflag = true;
        }
      }
    }

    return (
      <PageHeaderWrapper title="二号基金股票风控">
        <Card bordered={false}>
          {listData.list.length === 0 ? (
            <div
              style={{
                textAlign: 'center',
                borderRadius: 4,
                marginBottom: 20,
                marginTop: 20,
                padding: '30 50',
                margin: '20 20',
              }}
            >
              {' '}
              <Spin size="large" />{' '}
            </div>
          ) : (
            <StandardTable
              id="asd"
              selectedRows={selectedRows}
              loading={listLoading}
              data={listData}
              pagination={false}
              columns={this.columns}
              className={styles.TableLayout}
              // expandRowByClick={true}
              defaultExpandedRowKeys={expandedRowKeys}
              expandedRowRender={record => (
                <p style={{ margin: 0 }}>
                  <span style={{ margin: '6px', fontWeight: '600' }}>事件备注:</span>
                  <span>
                    {record.mark === undefined || record.mark === '' ? '暂无' : record.mark}
                  </span>
                </p>
              )}
              rowKey="id"
              scroll={{ x: 1920, y: 618 }}
              rowClassName={(record, index) => {
                return record.colorflag ? styles.waring_color : '';
              }}
            />
          )}
        </Card>
        <RiskDetail
          record={record}
          RiskDetailVisible={RiskDetailVisible}
          closeRecord={this.closeRecord.bind(this)}
        />
        <BackTop visibilityHeight={95} />
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;

    /* 导入列表数据 */
    dispatch({
      type: 'riskstock/GetRiskDataTwo',
      payload: {},
      callback: res => {
        this.timeout = setTimeout(() => {
          const mover = new Mover(document.querySelectorAll('.ant-table-body')[0]);
        }, 1200);
      },
    });
  }

  componentWillUnmount() {}
}

export default RiskControlTwo;
